<?php

namespace app\api\controller\api;

use app\common\controller\BasicApi;
use app\common\library\Sms as Smslib;
use think\facade\Hook;
/**
 * 手机短信接口
 */
class Sms extends BasicApi
{

    /**
     * 发送验证码
     * @ApiTitle    (发送验证码)
     * @ApiMethod   (GET)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="event", type="string", required=true, description="事件名称: register【注册】，bindmobile【绑定手机号】,resetpwd【重置密码】")
     * @ApiReturn   ({'code':'200','msg':'响应成功'})
     */
    public function send()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : '';
        if (!$mobile || !isMobile($mobile)) {
            $this->error('手机号不正确');
        }
        if (!Smslib::frequencyLimit($mobile,$event)) {
            $this->error('发送频繁，请稍后重试！');
        }
        if(!Smslib::ipLimit()){
            $this->error('单位时间内的短信量有限，请慎重使用！');
        }
        if(Hook::get('Sms' . ucfirst($event))){
            if( ($msg = Hook::listen('Sms' . ucfirst($event), $mobile)) !== true){
                $this->error($msg);
            }
        }
        $ret = Smslib::send($mobile, NULL, $event);
        if ($ret) {
            $this->success('发送成功');
        } else {
            $this->error('发送失败');
        }
    }

    /**
     * 检测验证码
     * @ApiTitle    (检测验证码)
     * @ApiMethod   (GET)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="event", type="string", required=true, description="事件名称: register【注册】，bindmobile【绑定手机号】,resetpwd【重置密码】")
     * @ApiParams   (name="captcha", type="string", required=true, description="验证码")
     * @ApiReturn   ({'code':'200','msg':'校验成功'})
     */
    public function check()
    {
        $mobile = $this->request->request("mobile");
        $event = $this->request->request("event");
        $event = $event ? $event : 'register';
        $captcha = $this->request->request("captcha");
        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号不正确');
        }
        if(Hook::get('Sms' . ucfirst($event))){
            if( ($msg = Hook::listen('Sms' . ucfirst($event), $mobile)) !== true){
                $this->error($msg);
            }
        }
        $ret = Smslib::check($mobile, $captcha, $event);
        if ($ret) {
            $this->success('校验成功' );
        } else {
            $this->error('验证码不正确');
        }

    }

}
